package _04_queue.my_implements;

import _04_queue.AbstractQueue;

import java.util.Iterator;

/**
 * @author: mornd
 * @dateTime: 2023/6/4 - 22:10
 * 单向环形带哨兵的链表（推荐使用）
 * 内部创建 Node 内部类，head，tail 都是 Node 类型
 */
public class LinkedListQueue<E> extends AbstractQueue<E> {
    /**
     * 节点数
     */
    private int size;

    /**
     * 容量
     */
    private int capacity = Integer.MAX_VALUE;

    /**
     * 头节点
     * 头节点就是哨兵节点，尾节点就是存储最后一个元素的节点
     */
    Node<E> head;

    /**
     * 尾节点
     */
    Node<E> tail;

    /**
     * 头节点的值
     */
    private static final Object VAL = new Object();

    /**
     * 初始化执行
     */
    {
        head = new Node(VAL);
        tail = head;
        head.next = head;
    }

    public LinkedListQueue() {
    }

    public LinkedListQueue(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public boolean offer(E e) {
        if(isFull()) {
            return false;
        }
        Node<E> added = new Node<>(e, head);
        tail.next = added;
        tail = added;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (head.next == head) {
            return null;
        }
        Node<E> first = head.next;
        head.next = first.next;
        if (first == tail) {
            tail = head.next;
        }
        size--;
        return first.value;
    }

    @Override
    public E peek() {
        if (head.next == head) {
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return (head == tail);
    }

    @Override
    public void clear() {
        for (Node<E> x = head.next; x != tail; ) {
            Node<E> next = x.next;
            x.value = null;
            x.next = null;
            x = next;
        }
        if(head != tail) {
            tail = head;
            head.next = tail;
            size = 0;
        }

    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Itr();
    }

    private static class Node<E> {
        /**
         * 存储的值
         */
        E value;

        /**
         * 下一个节点
         */
        Node<E> next;

        public Node() {
        }

        public Node(E value) {
            this.value = value;
        }

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    /**
     * 迭代器对象
     */
    private class Itr implements Iterator<E> {
        private Node<E> p = head.next;

        @Override
        public boolean hasNext() {
            return p != head;
        }

        @Override
        public E next() {
            E value = p.value;
            p = p.next;
            return value;
        }
    }
}
